package com.example.demo.utils;

import javax.persistence.AttributeConverter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author shenb
 * @date 2022-09-15 10:50
 */
public class JsonAttributeConverter {
    public static class MapConverter implements AttributeConverter<Map<String, String>, String>, Serializable {
        @Override
        public String convertToDatabaseColumn(Map<String, String> attribute) {
            return JsonUtils.toJson(Optional.ofNullable(attribute).orElse(Collections.EMPTY_MAP));
        }

        @Override
        public Map<String, String> convertToEntityAttribute(String dbData) {
            return Optional.ofNullable(JsonUtils.fromJsonAsMap(dbData, String.class, String.class)).orElse(new HashMap<>());
        }
    }

    public static class ListConverter implements AttributeConverter<List<String>, String>, Serializable {
        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            return JsonUtils.toJson(Optional.ofNullable(attribute).orElse(Collections.emptyList()));
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            return Optional.ofNullable(JsonUtils.fromJsonAsList(dbData, String.class)).orElse(new ArrayList<>());
        }
    }
}
